// BoLe HR Platform - 主要JavaScript逻辑

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

function initializeApp() {
    // 初始化导航
    initializeNavigation();
    
    // 强制启用演示模式
    if (window.location.hostname === 'localhost' || 
        window.location.hostname === '127.0.0.1' || 
        window.location.hostname.includes('10.112.140.137') ||
        window.location.port === '3000') {
        console.log('🧪 强制启用演示模式');
        enableGlobalDemoMode();
    }
    
    // 显示默认页面
    showSection('home');
    
    // 绑定全局事件
    bindGlobalEvents();
    
    // 检查认证状态
    if (authManager) {
        authManager.checkAuthStatus();
    }
}

// 全局演示模式启用
function enableGlobalDemoMode() {
    // 创建演示用户
    const demoUser = {
        id: 'demo-hr-global',
        username: 'Demo HR',
        email: 'hr@demo.com',
        user_type: 'hr',
        is_demo: true,
        is_test: true,
        token: 'demo-global-token'
    };
    
    // 存储到所有可能的localStorage键
    localStorage.setItem('user', JSON.stringify(demoUser));
    localStorage.setItem('currentUser', JSON.stringify(demoUser));
    localStorage.setItem('access_token', demoUser.token);
    localStorage.setItem('authToken', demoUser.token);
    
    // 确保authManager同步
    if (window.authManager) {
        authManager.currentUser = demoUser;
    }
    
    console.log('✅ 演示模式用户已设置:', demoUser);
}

function initializeNavigation() {
    // 移动端导航切换
    const navToggle = document.getElementById('navToggle');
    const navMenu = document.getElementById('navMenu');
    
    if (navToggle && navMenu) {
        navToggle.addEventListener('click', function() {
            navMenu.classList.toggle('active');
            navToggle.classList.toggle('active');
        });
    }
    
    // 点击其他地方关闭导航
    document.addEventListener('click', function(event) {
        if (!navToggle.contains(event.target) && !navMenu.contains(event.target)) {
            navMenu.classList.remove('active');
            navToggle.classList.remove('active');
        }
    });
}

function bindGlobalEvents() {
    // 监听窗口大小变化
    window.addEventListener('resize', function() {
        // 处理响应式布局调整
        handleResponsiveLayout();
    });
    
    // 监听键盘事件
    document.addEventListener('keydown', function(event) {
        // ESC键关闭模态框
        if (event.key === 'Escape') {
            closeModal();
        }
    });
    
    // 监听表单输入事件
    document.addEventListener('input', function(event) {
        if (event.target.matches('input[required], select[required]')) {
            // 清除错误状态
            event.target.style.borderColor = 'var(--border-color)';
        }
    });
}

function handleResponsiveLayout() {
    // 处理移动端布局调整
    const screenWidth = window.innerWidth;
    
    if (screenWidth <= 768) {
        // 移动端布局
        adjustMobileLayout();
    } else {
        // 桌面端布局
        adjustDesktopLayout();
    }
}

function adjustMobileLayout() {
    // 移动端特殊处理
    const dashboardNavs = document.querySelectorAll('.dashboard-nav');
    dashboardNavs.forEach(nav => {
        nav.style.overflowX = 'auto';
    });
}

function adjustDesktopLayout() {
    // 桌面端特殊处理
    const dashboardNavs = document.querySelectorAll('.dashboard-nav');
    dashboardNavs.forEach(nav => {
        nav.style.overflowX = 'visible';
    });
}

// 页面导航
function showSection(sectionName) {
    // 隐藏所有页面
    const sections = document.querySelectorAll('.section');
    sections.forEach(section => {
        section.classList.remove('active');
    });
    
    // 显示指定页面
    const targetSection = document.getElementById(sectionName);
    if (targetSection) {
        targetSection.classList.add('active');
        
        // 页面特殊处理
        handleSectionSpecific(sectionName);
    }
}

function handleSectionSpecific(sectionName) {
    switch(sectionName) {
        case 'home':
            // 首页特殊处理
            break;
        case 'hr-dashboard':
            // HR仪表板初始化
            if (window.hrManager && authManager.isHR()) {
                hrManager.init();
            }
            break;
        case 'candidate-dashboard':
            // 求职者仪表板初始化
            if (window.candidateManager && authManager.isCandidate()) {
                candidateManager.init();
            }
            break;
    }
}

// 功能展示
function showFeatures() {
    const featuresSection = document.getElementById('features');
    if (featuresSection) {
        featuresSection.scrollIntoView({ 
            behavior: 'smooth',
            block: 'start' 
        });
    }
}

// 角色选择进入
function enterAsRole(role) {
    // 创建演示用户数据
    const demoUserData = {
        hr: {
            id: 'demo-hr-001',
            username: 'Demo HR',
            email: 'hr@demo.com',
            user_type: 'hr',
            company_name: '演示公司',
            token: 'demo-hr-token'
        },
        candidate: {
            id: 'demo-candidate-001',
            username: 'Demo 求职者',
            email: 'candidate@demo.com', 
            user_type: 'candidate',
            token: 'demo-candidate-token'
        }
    };

    // 设置演示用户数据
    const userData = demoUserData[role];
    if (userData) {
        // 存储到localStorage模拟登录状态 (与auth.js保持一致)
        localStorage.setItem('user', JSON.stringify(userData));
        localStorage.setItem('currentUser', JSON.stringify(userData));
        localStorage.setItem('access_token', userData.token);
        localStorage.setItem('authToken', userData.token);
        
        // 同步到authManager
        if (window.authManager) {
            authManager.currentUser = userData;
        }
        
        // 显示相应的仪表板
        if (role === 'hr') {
            showToast('欢迎进入HR演示模式！', 'success');
            showSection('hr-dashboard');
            // 立即初始化HR仪表板
            if (window.hrManager) {
                hrManager.init();
            }
        } else if (role === 'candidate') {
            showToast('欢迎进入求职者演示模式！', 'success');
            showSection('candidate-dashboard');
            // 立即初始化候选人仪表板
            if (window.candidateManager) {
                candidateManager.init();
            }
        }
        
        // 更新导航栏
        updateNavigation(role);
    }
}

// 更新导航栏
function updateNavigation(role) {
    const navMenu = document.getElementById('navMenu');
    if (navMenu) {
        if (role === 'hr') {
            navMenu.innerHTML = `
                <a href="#" class="nav-link" onclick="showSection('hr-dashboard')">HR仪表板</a>
                <a href="#" class="nav-link" onclick="logout()">退出</a>
            `;
        } else if (role === 'candidate') {
            navMenu.innerHTML = `
                <a href="#" class="nav-link" onclick="showSection('candidate-dashboard')">求职者仪表板</a>
                <a href="#" class="nav-link" onclick="logout()">退出</a>
            `;
        }
    }
}

// 退出登录
function logout() {
    // 清除本地存储
    localStorage.removeItem('currentUser');
    localStorage.removeItem('authToken');
    
    // 重置导航栏
    const navMenu = document.getElementById('navMenu');
    if (navMenu) {
        navMenu.innerHTML = `
            <a href="#" class="nav-link" onclick="showSection('home')">首页</a>
            <a href="#" class="nav-link" onclick="showSection('role-select')">选择角色</a>
        `;
    }
    
    // 返回首页
    showToast('已退出演示模式', 'info');
    setTimeout(() => {
        showSection('home');
    }, 1000);
}

// 模态框管理
function showModal() {
    const modal = document.getElementById('modal');
    if (modal) {
        modal.style.display = 'block';
        document.body.style.overflow = 'hidden';
        
        // 添加动画效果
        setTimeout(() => {
            modal.classList.add('show');
        }, 10);
    }
}

function closeModal() {
    const modal = document.getElementById('modal');
    if (modal) {
        modal.classList.remove('show');
        document.body.style.overflow = 'auto';
        
        // 延迟隐藏以完成动画
        setTimeout(() => {
            modal.style.display = 'none';
        }, 300);
    }
}

// 点击模态框背景关闭
document.addEventListener('click', function(event) {
    const modal = document.getElementById('modal');
    if (event.target === modal) {
        closeModal();
    }
});

// 工具函数
function scrollToTop() {
    window.scrollTo({
        top: 0,
        behavior: 'smooth'
    });
}

function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(function() {
        showToast('已复制到剪贴板', 'success');
    }).catch(function() {
        showToast('复制失败', 'error');
    });
}

function downloadFile(url, filename) {
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

function generateRandomId() {
    return Math.random().toString(36).substr(2, 9);
}

function sanitizeInput(input) {
    const div = document.createElement('div');
    div.textContent = input;
    return div.innerHTML;
}

// 数据格式化工具
function formatNumber(num, precision = 0) {
    return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: precision,
        maximumFractionDigits: precision
    }).format(num);
}

function formatPercent(value) {
    return new Intl.NumberFormat('zh-CN', {
        style: 'percent',
        minimumFractionDigits: 1,
        maximumFractionDigits: 1
    }).format(value / 100);
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 搜索和过滤工具
function highlightSearchTerms(text, searchTerms) {
    let highlightedText = text;
    
    searchTerms.forEach(term => {
        const regex = new RegExp(`(${term})`, 'gi');
        highlightedText = highlightedText.replace(regex, '<mark>$1</mark>');
    });
    
    return highlightedText;
}

function filterArray(array, searchTerm, searchFields) {
    if (!searchTerm) return array;
    
    const lowerSearchTerm = searchTerm.toLowerCase();
    
    return array.filter(item => {
        return searchFields.some(field => {
            const value = getNestedProperty(item, field);
            return value && value.toString().toLowerCase().includes(lowerSearchTerm);
        });
    });
}

function getNestedProperty(obj, path) {
    return path.split('.').reduce((current, prop) => current && current[prop], obj);
}

// 排序工具
function sortArray(array, sortField, sortDirection = 'asc') {
    return [...array].sort((a, b) => {
        const aValue = getNestedProperty(a, sortField);
        const bValue = getNestedProperty(b, sortField);
        
        if (aValue < bValue) return sortDirection === 'asc' ? -1 : 1;
        if (aValue > bValue) return sortDirection === 'asc' ? 1 : -1;
        return 0;
    });
}

// 表单验证工具
function validateRequired(formElement) {
    const requiredFields = formElement.querySelectorAll('[required]');
    let isValid = true;
    
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            field.classList.add('error');
            isValid = false;
        } else {
            field.classList.remove('error');
        }
    });
    
    return isValid;
}

function validatePassword(password) {
    const minLength = 8;
    const hasUpperCase = /[A-Z]/.test(password);
    const hasLowerCase = /[a-z]/.test(password);
    const hasNumbers = /\d/.test(password);
    const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password);
    
    const errors = [];
    
    if (password.length < minLength) {
        errors.push(`密码长度至少${minLength}位`);
    }
    
    if (!hasUpperCase) {
        errors.push('密码需包含大写字母');
    }
    
    if (!hasLowerCase) {
        errors.push('密码需包含小写字母');
    }
    
    if (!hasNumbers) {
        errors.push('密码需包含数字');
    }
    
    if (!hasSpecialChar) {
        errors.push('密码需包含特殊字符');
    }
    
    return {
        isValid: errors.length === 0,
        errors: errors
    };
}

// 本地存储工具
function saveToLocalStorage(key, data) {
    try {
        localStorage.setItem(key, JSON.stringify(data));
        return true;
    } catch (error) {
        console.error('Failed to save to localStorage:', error);
        return false;
    }
}

function loadFromLocalStorage(key, defaultValue = null) {
    try {
        const stored = localStorage.getItem(key);
        return stored ? JSON.parse(stored) : defaultValue;
    } catch (error) {
        console.error('Failed to load from localStorage:', error);
        return defaultValue;
    }
}

function removeFromLocalStorage(key) {
    try {
        localStorage.removeItem(key);
        return true;
    } catch (error) {
        console.error('Failed to remove from localStorage:', error);
        return false;
    }
}

// 网络状态检测
function checkNetworkStatus() {
    return navigator.onLine;
}

window.addEventListener('online', function() {
    showToast('网络连接已恢复', 'success');
});

window.addEventListener('offline', function() {
    showToast('网络连接已断开', 'warning');
});

// 性能监控
function measurePerformance(name, fn) {
    const start = performance.now();
    const result = fn();
    const end = performance.now();
    
    console.log(`${name} took ${end - start} milliseconds`);
    return result;
}

// 错误处理
window.addEventListener('error', function(event) {
    console.error('Global error:', event.error);
    showToast('发生了未知错误，请刷新页面重试', 'error');
});

window.addEventListener('unhandledrejection', function(event) {
    console.error('Unhandled promise rejection:', event.reason);
    showToast('网络请求失败，请检查网络连接', 'error');
});

// 页面可见性变化处理
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        // 页面隐藏时的处理
        console.log('Page hidden');
    } else {
        // 页面显示时的处理
        console.log('Page visible');
        
        // 重新验证认证状态
        if (authManager && authManager.isAuthenticated()) {
            authManager.checkAuthStatus();
        }
    }
});

// 添加CSS样式到头部
function addStyleToHead() {
    const style = document.createElement('style');
    style.textContent = `
        /* 动态添加的样式 */
        .skill-tag {
            display: inline-block;
            padding: 0.25rem 0.5rem;
            margin: 0.125rem;
            background: var(--light-color);
            border: 1px solid var(--border-color);
            border-radius: 15px;
            font-size: 0.875rem;
            color: var(--dark-color);
        }
        
        .skill-match {
            background: #d1e7dd;
            border-color: var(--success-color);
            color: var(--success-color);
        }
        
        .skill-missing {
            background: #f8d7da;
            border-color: var(--danger-color);
            color: var(--danger-color);
        }
        
        .score-badge {
            background: var(--primary-color);
            color: white;
            padding: 0.25rem 0.5rem;
            border-radius: 12px;
            font-size: 0.875rem;
            font-weight: 500;
        }
        
        .upload-area {
            border: 2px dashed var(--border-color);
            border-radius: 10px;
            padding: 2rem;
            text-align: center;
            margin-bottom: 1rem;
        }
        
        .upload-prompt {
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .upload-prompt:hover {
            border-color: var(--primary-color);
            background: var(--light-color);
        }
        
        .upload-tips {
            background: var(--light-color);
            padding: 1rem;
            border-radius: 8px;
            border-left: 4px solid var(--info-color);
        }
        
        .upload-tips h4 {
            margin-bottom: 0.5rem;
            color: var(--info-color);
        }
        
        .upload-tips ul {
            margin: 0;
            padding-left: 1.5rem;
        }
        
        .upload-tips li {
            margin-bottom: 0.25rem;
            color: var(--secondary-color);
        }
        
        .modal.show {
            opacity: 1;
        }
        
        .modal.show .modal-content {
            transform: translateY(0);
        }
        
        .error-state, .empty-state {
            text-align: center;
            padding: 2rem;
            color: var(--secondary-color);
        }
        
        .error-state i, .empty-state i {
            font-size: 3rem;
            margin-bottom: 1rem;
            opacity: 0.5;
        }
        
        .status-select {
            padding: 0.5rem;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-size: 0.875rem;
        }
        
        .form-actions {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
            margin-top: 2rem;
            padding-top: 1rem;
            border-top: 1px solid var(--border-color);
        }
        
        @media (max-width: 480px) {
            .form-actions {
                flex-direction: column;
            }
        }
    `;
    
    document.head.appendChild(style);
}

// 页面加载完成后添加样式
document.addEventListener('DOMContentLoaded', addStyleToHead);

// 导出常用功能供其他模块使用
window.BoLeUtils = {
    showToast,
    showLoading,
    showError,
    showEmpty,
    formatDate,
    formatCurrency,
    formatNumber,
    formatPercent,
    formatFileSize,
    debounce,
    validateEmail,
    validateForm,
    sanitizeInput,
    copyToClipboard,
    downloadFile,
    saveToLocalStorage,
    loadFromLocalStorage,
    removeFromLocalStorage
};